<template>
    
    <div style="display: flex; gap: 20px; padding: 20px;">
        <!-- 左侧表单 -->
        <div style="flex: 1;">
            <el-form ref="ruleFormRef" :model="ruleForms" :rules="rules" label-width="auto" style="max-width: 600px;">
                <!-- 基础信息 -->
                <h3>基础信息</h3>

                <el-form-item label="开票单号">
                    <div style="display: flex; justify-content: center;">
                        <el-input v-model="ruleForms.invoicingCode" :disabled="autoGenerate" />
                        <el-checkbox v-model="autoGenerate" style="margin-left: 10px;">系统编号</el-checkbox>
                    </div>
                </el-form-item>

                <el-form-item label="开票主体">
                    <el-input v-model="ruleForms.invoicingName" />
                </el-form-item>



                <el-form-item label="发票类型">
                    <el-select style="width: 300px;" v-model="ruleForms.invoicingType" placeholder=""
                        clearable>
                        <el-option label="专用发票" value="专用发票" />
                        <el-option label="普通发票" value="普通发票" />
                        <el-option label="电子发票" value="电子发票" />
                        <el-option label="其他" value="其他" />
                    </el-select>
                </el-form-item>
                <el-form-item label="开票金额">
                    <el-input v-model="ruleForms.invoicingMomeny" />
                </el-form-item>
                <el-form-item label="开票方">
                    <el-select style="width: 300px;" v-model="ruleForms.receiveInvoicing" placeholder=""
                        clearable>
                        <el-option label="白读公司" value="白读公司" />
                        <el-option label="梅团公司" value="梅团公司" />
                        <el-option label="腾旭公司" value="腾旭公司" />
                        <el-option label="景东公司" value="景东公司" />
                    </el-select>
                </el-form-item>
                <el-form-item label="开票时间" prop="remarks">
                    <el-input type="date" v-model="ruleForms.invoicingDate" />
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                    <el-input v-model="ruleForms.invoicingDesc" type="textarea" />
                </el-form-item>

                <!-- 加工工序 -->
                <h3>加工工序</h3>
                <div style="display: flex; gap: 10px; margin-bottom: 10px;">
                    <el-button type="primary" size="small" @click="showAddStepDialog = true">添加</el-button>
                    <el-button type="danger" size="small" @click="removeSelectedSteps()">移除</el-button>
                </div>

                <el-table :data="orderSteps" style="width: 1300px; min-width: 1300px; overflow-x: auto;" border
                    @selection-change="handleSelectionChange">
                    <!-- 列定义保持不变 -->
                </el-table>

                <el-table :data="orderSteps" style="width: 1300px; min-width: 1300px; overflow-x: auto;" border
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="序号" width="80">
                        <template #default="{ $index }">
                            {{ $index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="订单编号" min-width="120">
                        <template #default="{ row }">
                            {{ row.orderCode }}
                        </template>
                    </el-table-column>
                    <el-table-column label="订单数量" min-width="150">
                        <template #default="{ row }">
                            {{ row.orderNum }}
                        </template>
                    </el-table-column>
                    <el-table-column label="订购物品" min-width="200">
                        <template #default="{ row }">
                            {{ row.orderGoods }}
                        </template>
                    </el-table-column>
                    <el-table-column label="总金额" min-width="120">
                        <template #default="{ row }">
                            {{ row.allmomeny }}
                        </template>
                    </el-table-column>
                    <el-table-column label="已付金额" min-width="150">
                        <template #default="{ row }">
                            {{ row.tomomeny }}
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" min-width="200">
                        <template #default="{ row }">
                            <el-input v-model="row.invoicingDesc" size="small" style="width: 100%;" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" min-width="240" fixed="right">
                        <template #default="{ $index }">
                            <el-button size="small" @click="moveUp($index)">上移</el-button>
                            <el-button size="small" @click="moveDown($index)">下移</el-button>
                            <el-button size="small" type="danger" @click="removeStep($index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div style="text-align: right; margin-top: 20px;">
                    <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
                </div>
            </el-form>
        </div>

        <!-- 右侧添加工序弹窗 -->
        <div style="width: 1000px;">
            <el-dialog title="添加订单" v-model="showAddStepDialog" width="1000px">
                
                <el-table :data="availableSteps" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="序号" width="60">
                        <template #default="{ $index }">
                            {{ $index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="销售订单编号" min-width="120">
                        <template #default="{ row }">
                            {{ row.orderCode }}

                        </template>
                    </el-table-column>
                    <el-table-column label="下单人" min-width="150">
                        <template #default="{ row }">
                            {{ row.orderNum }}
                        </template>
                    </el-table-column>
                    <el-table-column label="订单状态" min-width="120">
                        <template #default="{ row }">
                            {{ row.orderGoods }}
                        </template>
                    </el-table-column>
                    <el-table-column label="下单商品" min-width="150">
                        <template #default="{ row }">
                            {{ row.allmomeny }}
                        </template>
                    </el-table-column>
                    <el-table-column label="订单数量" min-width="150">
                        <template #default="{ row }">
                            {{ row.tomomeny }}
                        </template>
                    </el-table-column>
                </el-table>

                <div style="margin-top: 20px; text-align: right;">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalSteps"
                        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"></el-pagination>
                </div>

                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="showAddStepDialog = false">取消</el-button>
                        <el-button type="primary" @click="addSelectedSteps">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios'
import router from '@/router';
import { log } from 'echarts/types/src/util/log.js';

// ==================== 接口返回数据类型定义 ====================


interface orderStep {
    orderCode: string,
    orderSon: string,
    orderState: number,
    orderNum: number,
    orderGoods: string,
    allmomeny: number,
    tomomeny: number,
    clientId: number,
    isOrder: false,
    createrPeople: string,
    createTime: Date,
    updaterPeople: string,
    updateTime: Date,
    id: number,
    isDel: boolean
}
interface ProcessResponse {
    totalcount: number;
    totalPage: orderStep[];
}

interface Account {
    id: number;
    realName: string;
}

interface Department {
    id: number;
    departmentName: string;
}

// ==================== 表单数据 ====================
const ruleFormRef = ref<FormInstance>()

const ruleForms = reactive({
    "invoicingCode": "",
    "invoicingName": "",
    "invoicingType": "",
    "invoicingDate": "",
    "invoicingMomeny": "",
    "receiveInvoicing": "",
    "invoicingDesc": "",
})
// 自动生成编号
const autoGenerate = ref(false)
watch(autoGenerate, (val) => {
    if (val) {
        ruleForms.invoicingCode = `CP${Date.now()}${Math.floor(Math.random() * 10000)}`
    } else {
        ruleForms.invoicingCode = ''
    }
})




// 加工工序列表（已选）

const orderSteps = ref<orderStep[]>([])
// 添加工序弹窗
const showAddStepDialog = ref(false)

// 可用工序列表
const availableSteps = ref<orderStep[]>([])
const totalSteps = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)

const fetchAvailableSteps = () => {
    axios.get<ProcessResponse>(`api/InvoiceTicket/Getorder`, {
        params: {
            Index: currentPage.value,
            size: pageSize.value
        }
    })
        .then(res => {
            availableSteps.value = res.data.totalPage || []
            totalSteps.value = res.data.totalcount
        })
        .catch(err => console.error('获取工序失败:', err))
}

// 事件处理
const selectedStepIds = ref<number[]>([])

const handleSelectionChange = (selection: orderStep[]) => {
    selectedStepIds.value = selection.map(s => s.id)
}

const addSelectedSteps = () => {
    const newSteps = availableSteps.value.filter(step => selectedStepIds.value.includes(step.id))
    orderSteps.value.push(...newSteps)
    showAddStepDialog.value = false
    selectedStepIds.value = []
}

const removeStep = (index: number) => {
    orderSteps.value.splice(index, 1)
}

const moveUp = (index: number) => {
    if (index > 0) {
        const temp = orderSteps.value[index]
        orderSteps.value[index] = orderSteps.value[index - 1]
        orderSteps.value[index - 1] = temp
    }
}

const moveDown = (index: number) => {
    if (index < orderSteps.value.length - 1) {
        const temp = orderSteps.value[index]
        orderSteps.value[index] = orderSteps.value[index + 1]
        orderSteps.value[index + 1] = temp
    }
}

const removeSelectedSteps = () => {
    orderSteps.value = orderSteps.value.filter(step => !selectedStepIds.value.includes(step.id))
    selectedStepIds.value = []
}

const handleSizeChange = (val: number) => {
    pageSize.value = val
    fetchAvailableSteps()
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
    fetchAvailableSteps()
}

// 表单验证规则
const rules = reactive<FormRules>({
    flowCode: [
        { required: true, message: '请输入工艺流程编号', trigger: 'blur' }
    ],
    flowName: [
        { required: true, message: '请输入工艺流程名称', trigger: 'blur' }
    ],
    personId: [
        { required: true, message: '请选择负责人', trigger: 'change' }
    ],
    departmentId: [
        { required: true, message: '请选择所属部门', trigger: 'change' }
    ]
})

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const payload = {
                invoicingCode: ruleForms.invoicingCode,
                invoicingName: ruleForms.invoicingName,
                invoicingType: ruleForms.invoicingType,
                invoicingDate: ruleForms.invoicingDate,
                invoicingDesc: ruleForms.invoicingDesc,
                invoicingMomeny: ruleForms.invoicingMomeny,
                receiveInvoicing: ruleForms.receiveInvoicing,

                orderdtos: orderSteps.value.map(step => ({
                    orderCode: step.orderCode,
                    orderNum: step.orderNum,
                    orderGoods: step.orderGoods,
                    allmomeny: step.allmomeny,
                    tomomeny: step.tomomeny,
                    clientId: step.clientId
                }))
            }

            axios.post('/api/InvoiceTicket/AddInvoice', payload)
                .then(() => {
                    ElMessage.success('创建成功')
                    
                    resetForm(formEl)
                    orderSteps.value = []
                })
                .catch(err => {
                    if (err.response?.status === 404) {
                        ElMessage.error('接口不存在，请检查后端服务或路径')
                    } else if (err.response?.status === 400) {
                        ElMessage.error('请求参数错误，请检查数据格式')
                    } else {
                        ElMessage.error('创建失败，请联系管理员')
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    router.push({ path: "/ProcessFlow" })
}

// 页面挂载时初始化
onMounted(() => {
    fetchAvailableSteps()
})
</script>

<style scoped>
.dialog-footer {
    text-align: right;
}
</style>